 /* 
 * Copyright 2013 Imanuel Rohlfing, Dennis Wittkötter

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package management.beans;

import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.el.ELContext;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import management.constants.Names;
import management.ejb.DatabaseController;
import management.entities.*;


/**
 * Bean for IntUser objects.
 * This bean handles the database operations with the IntUser entities.
 * @author Imanuel Rohlfing
 */
@ManagedBean(name="intusers")
@SessionScoped
public class IntUserBean implements Serializable {
    /**
     * The database controller
     */
    @EJB
    private DatabaseController dbC;
    
    /**
     * The current user
     */
    private IntUser user = new IntUser();
    
    /**
     * A list of all users stored in the database.
     */
    private List<IntUser> allUser;

    /**
     * a LoginBean
     */
    private LoginBean loginBean;  
    
    /**
     * Default constructor
     */
    public IntUserBean(){
        loginBean = (LoginBean)getBean("auth", LoginBean.class);
    }
   
    /**
     * Reads all users from the database and stores them to a local field.
     * Will be called after object construction.
     */
    @PostConstruct
    public void loadIntUserList() {
        allUser = dbC.getIntUsers();
    }

    /**
     * Persists the commited user to the database.
     * @param u the user that should be stored into the database.
     * @return  link path for website redirection
     */
    public String add(IntUser u){
        try {
            if(dbC.intUserExists(u)){
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, Names.MSG_INTUSER_ALREADY_EXISTS, ""));
            }
            else if( dbC.persist(u) ){
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, Names.MSG_INTUSER_CREATED_S, ""));
                loadIntUserList();
            }
            else{
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_INTUSER_CREATED_F, ""));                 
            }          
        } 
        catch(Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_INTUSER_CREATED_F, ""));
        }    
        u.setUsername(null);
        
        return "SHOW_INTUSER";
    }
    
    /**
     * Updates the current user in the database.
     * @return  link path for website redirection
     */
    public String edit(){
        try{
            if(dbC.intUserExists(user)){
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_INTUSER_ALREADY_EXISTS, ""));
                return "EDIT_INTUSER";
            }
            else if( dbC.update(user) ){
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, Names.MSG_INTUSER_EDITED_S, ""));
                loadIntUserList();
                user = new IntUser();                    
            }
            else{
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_INTUSER_EDITED_F, ""));
                return "EDIT_INTUSER";
            }           
        }
        catch(Exception e){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, Names.MSG_INTUSER_EDITED_F, ""));
            return "EDIT_INTUSER";
        }
        return "SHOW_INTUSER";
    }
    
    /**
     * Reads the id of an user from the current request parameter and searches for
     * the related user in the database. If found the user will be updated.
     * @return  link path for website redirection
     */
    public String gotoEdit() {
        String id = getRequestParameter("edit");
        user = dbC.findIntUser(id);
         if(user == null){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_INTUSER_DOESNT_EXIST, ""));
            return "SHOW_INTUSER";
        }
        return "EDIT_INTUSER";
    }

    /**
     * Reads the id of an user from the current request parameter and searches for
     * the related user in the database. If found the user will be deleted.
     * @return  link path for website redirection
     */
    public String gotoDelete() {
 
        String username = getRequestParameter("self");
        if(loginBean.getCurrentUser().equals(username)){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,Names.MSG_INTUSER_CANT_DELETE_OWN_ACCOUNT, ""));
            return "EDIT_INTUSER";
        }

        if( dbC.delete(user) ){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, Names.MSG_INTUSER_DELETED_S, ""));
            loadIntUserList();
            user = new IntUser();
            return "SHOW_INTUSER";
        }
        else{
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_INTUSER_DELETED_F, ""));
            return "EDIT_INTUSER";
        }
    }    
    
    /**
     * Provides the current user.
     * @return  the current user
     */
    public IntUser getUser(){
        return user;
    }
    
    /**
     * Provides all users from this object.
     * @return  all users
     */
    public List<IntUser> getIntUsers(){
        return allUser;
    }
    
    /**
     * Provides the value of the current request parameter.
     * @param par   faces parameter to read out
     * @return  value of the parameter
     */
    private String getRequestParameter(String par) { 
        return FacesContext.getCurrentInstance().getExternalContext()
                .getRequestParameterMap().get(par); 
    }   
    
     /**
     * Static method to get access to extern components.
     * @param <T>   type of the object of the component
     * @param beanName  name of the bean to get access on
     * @param clazz class of the bean to get access on
     * @return  the bean object to get access on
     */
    public static <T> T getBean(final String beanName, final Class<T> clazz) {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        return (T) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, beanName);
    } 

}